package com.ddm.controller;

import com.ddm.service.impl.FileService;
import com.dto.AjaxResult;
import com.entity.FileInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by he on 2025/5/18 17:03
 */
@RestController
@RequestMapping("/admin")
public class ImageController {
    @Autowired
    private FileService fileService;
    // 图片文件类型限制
    private static final List<String> ALLOWED_IMAGE_TYPES = Arrays.asList(
            "image/jpeg", "image/png", "image/gif", "image/bmp", "image/webp"
    );

    @PostMapping("/image")
    public AjaxResult uploadImage(@RequestParam("image") MultipartFile file) {
        try {
            //检查是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("上传文件不能为空");
            }
            //检查是否为图片
            String contentType = file.getContentType();
            if (contentType == null || !ALLOWED_IMAGE_TYPES.contains(contentType.toLowerCase())) {
                return AjaxResult.error("只支持上传图片文件，允许的格式: JPEG, PNG, GIF, BMP, WEBP");
            }
            //上传文件到OSS
            FileInfo fileInfo = fileService.uploadFile(file);
            if (fileInfo == null) {
                return AjaxResult.error("图片上传失败");
            }
            //获取图片URL
            String url = fileService.getPublicFileUrl(fileInfo.getFileName());
            if (url == null) {
                return AjaxResult.error("获取图片URL失败");
            }
            // 返回结果
            Map<String, String> data = new HashMap<>();
            data.put("url", url);
            return AjaxResult.success(data);

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统错误: " + e.getMessage());
        }
    }
}
